import time
import random

from src.database.connection import Neo4jInstance

graph = Neo4jInstance.get_connect()


# 功能函数部分
# # 在  pre_id next_id 两个节点中间，插入多个节点
# def mid_insert_node(pre_id, left_id, right_id, suf_id):
#     # 先删除 pre_id, next_id 的关系
#     graph.run(
#         """
#         MATCH (child {GlobalId: $suf_id})-[r:DEPENDENCE]->(parent {GlobalId: $pre_id})
#         DELETE r
#     """,
#         pre_id=pre_id,
#         suf_id=suf_id,
#     )
#
#     # 建立 pre_id 和 first_id 的连接
#     graph.run(
#         """
#         MATCH (parent {GlobalId: $pre_id}),(child {GlobalId: $left_id})
#         MERGE (child)-[:DEPENDENCE]->(parent)
#     """,
#         pre_id=pre_id,
#         left_id=left_id,
#     )
#
#     # 建立 last_id 和 next_id 的连接
#     graph.run(
#         """
#         MATCH (parent {GlobalId: $right_id}),(child {GlobalId: $suf_id})
#         MERGE (child)-[:DEPENDENCE]->(parent)
#     """,
#         right_id=right_id,
#         suf_id=suf_id,
#     )
#


# {父节点:子节点}
def segment_link(segment_map: {}):
    tx = graph.begin()
    for key, value in segment_map.items():
        tx.run(
            """
            MATCH (parent {GlobalId: $parent_id}),(child {GlobalId: $child_id})
            MERGE (child)-[:DEPENDENCE]->(parent)
        """,
            parent_id=key,
            child_id=value,
        )
    tx.commit()


def mid_insert_node_with_tx(pre_id, insert_id, suf_id, tx):
    tx.run(
        """
        MATCH (child {GlobalId: $suf_id})-[r:DEPENDENCE]->(parent {GlobalId: $pre_id})
        DELETE r
    """,
        pre_id=pre_id,
        suf_id=suf_id,
    )

    # 建立 pre_id 和 insert_id 的连接
    graph.run(
        """
        MATCH (parent {GlobalId: $pre_id}),(child {GlobalId: $insert_id})
        MERGE (child)-[:DEPENDENCE]->(parent)
    """,
        pre_id=pre_id,
        insert_id=insert_id,
    )

    # 建立 suf_id 和 next_id 的连接
    graph.run(
        """
        MATCH (parent {GlobalId: $insert_id}),(child {GlobalId: $suf_id})
        MERGE (child)-[:DEPENDENCE]->(parent)
    """,
        insert_id=insert_id,
        suf_id=suf_id,
    )


# 在 current_id 前面插入节点 new_id
def pre_insert_node(current_id, new_id):
    # 读取 current_id 的父节点
    ps = graph.run(
        """
        MATCH (c {GlobalId: $current_id})-[r:DEPENDENCE]->(p)
        RETURN p
    """,
        current_id=current_id,
    ).data()
    p_ids = [p["p"]["GlobalId"] for p in ps]
    if p_ids:
        for p_id in p_ids:
            graph.run(
                """
                MATCH (parent {GlobalId: $p_id}),(child {GlobalId: $new_id})
                MERGE (child)-[:DEPENDENCE]->(parent)
            """,
                p_id=p_id,
                new_id=new_id,
            )

    # 删除 current_id 和 原来的父节点 的关系
    graph.run(
        """
        MATCH (child {GlobalId: $current_id})-[r:DEPENDENCE]->(parent)
        DELETE r
    """,
        current_id=current_id,
    )

    graph.run(
        """
        MATCH (parent {GlobalId: $new_id}),(child {GlobalId: $current_id})
        MERGE (child)-[:DEPENDENCE]->(parent)
    """,
        new_id=new_id,
        current_id=current_id,
    )


# 在 current_id 后面插入节点 new_id
def suf_insert_node(current_id, new_id, tx):
    # 读取 current_id 的子节点
    cs = tx.run(
        """
    MATCH (c)-[r:DEPENDENCE]->(p {GlobalId: $current_id})
    RETURN c""",
        current_id=current_id,
    ).data()
    c_ids = [c["c"]["GlobalId"] for c in cs]
    if c_ids:
        for c_id in c_ids:
            # current_id 原来的子节点，依赖到 new_id
            tx.run(
                """
                MATCH (parent {GlobalId: $new_id}),(child {GlobalId: $c_id})
                MERGE (child)-[:DEPENDENCE]->(parent)
                """,
                new_id=new_id,
                c_id=c_id,
            )

    # 删除 current_id 和 原来的子节点 的关系
    tx.run(
        """
    MATCH (child)-[r:DEPENDENCE]->(parent {GlobalId: $current_id})
    DELETE r""",
        current_id=current_id,
    )
    # 建立关系
    tx.run(
        """
        MATCH (parent {GlobalId: $current_id}),(child {GlobalId: $new_id})
        MERGE (child)-[:DEPENDENCE]->(parent)
    """,
        current_id=current_id,
        new_id=new_id,
    )


# 节点数据更新
def update_node(nodes: []) -> []:
    # 定义批次大小
    batch_size = 1000

    # 分批次更新
    for i in range(0, len(nodes), batch_size):
        batch_updates = nodes[i : i + batch_size]
        cypher_query = """
            UNWIND $updates AS update
            MATCH (n {id: update.id})
            SET n += update
        """
        graph.run(cypher_query, updates=batch_updates)


def generate_virtual_id() -> str:
    # 生成一个0到99之间的随机整数
    random_number = random.randint(0, 99)
    # 将整数转换为两位数字的字符串形式
    random_string = str(random_number).rjust(2, "0")
    return "Virtual_" + str(int(round(time.time() * 1000000))) + "_" + random_string
